package com.one.blocks.security.authc.rememberme;

import com.one.blocks.security.config.properties.SecurityProperties;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-08-27 15:52:04
 */
public class RememberMeTokenFilter extends OncePerRequestFilter implements RememberMeFilter {

    private final TokenService tokenService;
    private final SecurityProperties props;
    public RememberMeTokenFilter(TokenService tokenService, SecurityProperties props) {
        this.tokenService = tokenService;
        this.props = props;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (!request.getRequestURI().equals(props.getLoginUrl()) && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 解析cookie
            UserDetails userDetails = tokenService.load(request);
            if (userDetails != null) {
                // 访问成功刷新会话
                tokenService.refreshIfNecessary(request, userDetails);
                // Store to SecurityContextHolder
                SecurityContextHolder.getContext().setAuthentication(createSuccessfulAuthentication(userDetails));
            }
        }
        // 无Authentication会导致登录自动失效
        chain.doFilter(request, response);
    }

    protected Authentication createSuccessfulAuthentication(UserDetails userDetails) {
        return new RememberMeAuthentication(true, userDetails);
    }
}
